#include "time_controller.h"
#include <iostream>
using namespace std;
using namespace adevs;

const double TimeController::DEFAULT_PHASE_LENGTH = 20.0;

TimeController::TimeController():
	Controller(), // Initialize the parent Atomic model
	// Initialize status variables
	remaining_time(0),
	current_side_green(-1)
{ // Initialize setting variables
	for (int i = 0;i < 4; i++)
		phase_length[i] = DEFAULT_PHASE_LENGTH;
}

void TimeController::delta_ext(double e, const Bag<IO_Type>& xb)
{
	remaining_time -= e;

	// Do nothing...
}
	
void TimeController::delta_int()
{
	current_side_green = next_side_green();
	remaining_time = phase_length[current_side_green];
}

void TimeController::delta_conf(const Bag<IO_Type>& xb)
{
}

void TimeController::output_func(Bag<IO_Type>& yb)
{
	if (current_side_green != -1)
	{
		IO_Type turn_off(out_semaphor_cmd(current_side_green), (io_type*)new SemaphorCommand(RED));
		yb.insert(turn_off);
	}

	IO_Type turn_on(out_semaphor_cmd(next_side_green()), (io_type*)new SemaphorCommand(GREEN));
	yb.insert(turn_on);
}

double TimeController::ta()
{
	if (current_side_green == -1) return 0;

	return remaining_time;
}

void TimeController::gc_output(Bag<IO_Type>& g)
{
	Bag<IO_Type>::iterator i;
	for (i = g.begin(); i != g.end(); i++)
	{
		delete (*i).value;
	}
}

TimeController::~TimeController()
{
}
